﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SysCommon.Tools
{
    /// <summary>
    /// 获取分页结果类
    /// </summary>
    /// <typeparam name="T">实体的类型</typeparam>
    public class GetResultFromPage<T> where T : new()
    {
        /// <summary>
        /// 对传入的数组进行分页，并返回指定的页
        /// </summary>
        /// <param name="inRecords">传入的数组</param>
        /// <param name="pageIndex">页码，从1开始</param>
        /// <param name="countsPerPage">每页的数量</param>
        /// <returns></returns>
        public static T[] GetPage(T[] inRecords, int PageIndex, int countsPerPage)
        {
            try
            {
                int pageIndex = PageIndex - 1;

                if (pageIndex < 0) return null;

                int sumCount = inRecords.Length;

                int startIndex = countsPerPage * pageIndex;
                int endIndex = countsPerPage * (pageIndex + 1);

                //如果起始索引超出界限
                if (startIndex >= sumCount)
                {
                    return null;
                }
                //如果指定页的数两小于每页的数两
                else if (endIndex > sumCount)
                {
                    endIndex = sumCount;
                }

                T[] res = new T[endIndex - startIndex];

                for (int i = 0; i < endIndex - startIndex; i++)
                {
                    res[i] = inRecords[i + startIndex];
                }

                return res;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用GetPage(T[] inRecords, int pageIndex, int countsPerPage)出错", ex);
            }
            return null;
        }
    }
}
